package com.icinfo.cloud.provider.punish.strategy.document;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.enums.DocumentTemplateTypeEnum;
import com.icinfo.cloud.provider.common.utils.PdfUtil;
import com.icinfo.cloud.provider.punish.document.DocumentFieldCustomConverter;
import com.icinfo.cloud.provider.punish.document.annotations.DocumentParamConvert;
import com.icinfo.cloud.provider.punish.document.dto.PrintDocumentBuildDto;
import com.icinfo.cloud.provider.punish.print.vo.ImageContentVo;
import com.icinfo.cloud.provider.punish.print.vo.PrintDocumentVo;
import com.icinfo.cloud.provider.punish.service.IAppCaseBeforeDocumentRecordService;
import com.icinfo.cloud.provider.punish.strategy.document.util.DocumentParamUtil;
import org.apache.commons.codec.binary.Base64;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 基础文书参数
 */
public interface BaseDocumentParam {
    /**
     * 获取窄幅文书参数
     *
     * @return 窄幅文书参数
     */
    default Map<String, Object> getNarrowParams() {
        return DocumentParamUtil.getDocumentParams(this, DocumentParamConvert::narrow);
    }

    /**
     * 获取宽幅文书参数
     *
     * @return 宽幅文书参数
     */
    default Map<String, Object> getStandardParams() {
        return DocumentParamUtil.getDocumentParams(this, DocumentParamConvert::standard);
    }

    /**
     * 根据参数map填充
     *
     * @param params       文书参数
     * @param templateType 文书类型，该参数是属于哪种文书类型的，则根据某种文书类型填充
     */
    default void fillFieldByParams(DocumentTemplateTypeEnum templateType, Map<String, Object> params) {
        Field[] fields = ReflectUtil.getFields(this.getClass());
        for (Field field : fields) {
            DocumentParamConvert convert = field.getAnnotation(DocumentParamConvert.class);
            if (Objects.isNull(convert)) {
                continue;
            }
            String fieldName = "";
            if (DocumentTemplateTypeEnum.STANDARD_TEMPLATE.equals(templateType)) {
                fieldName = convert.standard();
            } else {
                fieldName = convert.narrow();
            }
            //字段名为空则不需要填充 or 参数不存在该字段时跳过 or 如果是转换类则不用填充
            if (StrUtil.isEmpty(fieldName) || !params.containsKey(fieldName)
                    || DocumentFieldCustomConverter.class.isAssignableFrom(field.getType())) {
                continue;
            }
            ReflectUtil.setFieldValue(this, field, String.valueOf(params.get(fieldName)));
        }
    }


    /**
     * 转换图片url为base64
     *
     * @param url 图片url
     * @return 图片base64
     */
    default String convertImageUrlToBase64(String url) {
        if (StrUtil.isEmpty(url)) {
            return "";
        }
        try (HttpResponse response = HttpUtil.createGet(url).execute()) {
            byte[] bytes = response.bodyBytes();
            if (Objects.isNull(bytes)) {
                return "";
            }
            return "data:image/png;base64," + Base64.encodeBase64String(bytes);
        }
    }

    /**
     * 基于当前对象参数，组装打印内容
     *
     * @param dto 构建时需要的参数
     * @return 组装打印的结果
     */
    PrintDocumentVo assemblyPrintContent(PrintDocumentBuildDto dto);

    /**
     * 获取窄幅的地址
     *
     * @param addressWithLatAndLgt 窄幅的参数
     * @return
     */
    default String getNarrowCaseAddress(String addressWithLatAndLgt) {
        String address = "";
        try {
            JSONObject addressObj = JSON.parseObject(addressWithLatAndLgt);
            address = addressObj.getString("address");
        } catch (Exception e) {
            System.out.println("转换地址异常=>" + addressWithLatAndLgt);
        }
        return address;
    }

    /**
     * 增加当事人未签字原因
     *
     * @param imageInfo     json对象中图片对象集合
     * @param notSignReason 不签字理由
     */
    default void addNotSignReason(List<ImageContentVo> imageInfo, String notSignReason) {
        if (StrUtil.isEmpty(notSignReason)) {
            return;
        }
        imageInfo.add(new ImageContentVo()
                .setDescription(notSignReason)
                .setImageBase64(Collections.singletonList(""))
                .setImagePosition(1).setComment(Collections.emptyList()).initNormalStyle());
    }

    /**
     * 添加部门签章图片
     *
     * @param imageInfo json对象中图片对象集合
     * @param sealPic   签章pdf文件url       签章日期
     * @param dto       打印文书构建dto
     */
    default void addDeptSealPic(List<ImageContentVo> imageInfo, String sealPic, PrintDocumentBuildDto dto) {
        if (StrUtil.isEmpty(sealPic)) {
            //【v1.3.4】兼容历史数据，没有印章问题。v1.3.4之后生成的文书都添加sealPic字段
            sealPic = dto.getApplicationContext().getBean(IAppCaseBeforeDocumentRecordService.class)
                    .generateSealPicAgain(dto.getDocumentId());
        }
        //增加签章位
        imageInfo.add(new ImageContentVo()
                .setDescription("")
                .setImageBase64(Collections.singletonList(PdfUtil.pdfTransImage(sealPic)))
                .setImagePosition(3).setComment(Collections.emptyList()).initNormalStyle());
    }
}
